[求助]C#中的泛型中的元素能按指定下标取么?

来源:百度知道 编辑:UC知道 时间:2024/06/23 07:51:34
我现在有一个泛型对象的实例,我想取其中的第五个元素,能有办法像数组一样按下标取出来么?

你可以为该泛型定义一个索引器
用于获取或设置位于索引位置的元素.
当然,你需要确保该泛型类 从一个泛型集合类或接口继承.

代码如下
public class myList<T> : List<T>
{
public void Add(T item)
{
base.Add(item);
}

public T this[int index]
{
get
{
return base[index];
}
set
{
base[index] = value;
}
}
////
//TODO:附加其他业务处理
////
}
下面代码演示如何通过下标方式获取该集合内的元素
class Program
{
static void Main(string[] args)
{
myList<string> intList = new myList<string>();

intList.Add("White");
intList.Add("Yellow");
intList.Add("Blue");
intList.Add("Red");
intList.Add("Black");

for (int i = 0; i < intList.Count; i++)
Console.WriteLine(intList[i]);

Console.Read();
}
}

可以的。
List<User> list=new List<User>();
赋值语句